﻿using System;
using System.Windows;
using System.Windows.Threading;
using FPPrinter.Models;

namespace FPPrinter
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        private IAntiObject _antiObject;
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Handle exceptions in the UI thread
            this.DispatcherUnhandledException += OnDispatcherUnhandledException;

            // Handle exceptions in non-UI threads
            AppDomain.CurrentDomain.UnhandledException += OnAppDomainUnhandledException;
            
            
             _antiObject=AntiObject.Instance;
            
            var mainWindow = _antiObject.GetMainForm() ;
            mainWindow.Show();
        }

        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // Log the exception, show a message to the user, etc.
            MessageBox.Show("An unexpected error occurred: " + e.Exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

            // Optionally set e.Handled to true to prevent the application from crashing
            e.Handled = true;
        }

        private void OnAppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // Handle non-UI thread exceptions here
            if (e.ExceptionObject is Exception ex)
            {
                // Log the exception or take necessary actions
                MessageBox.Show("A non-UI thread error occurred: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Environment.Exit(-1);
            
            // The application will exit if this is not handled, as the runtime considers this a fatal error
        }

        protected override void OnExit(ExitEventArgs e)
        {
            // Optional: Unsubscribe from events when the application exits
            this.DispatcherUnhandledException -= OnDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException -= OnAppDomainUnhandledException;

            _antiObject.GetSys().Exist();
            base.OnExit(e);
        }
    }
}